//
//  ListViewModel.swift
//  TodoList
//
//  Created by 刘圣洁 on 2025/6/12.
//

import Foundation

/*
 增删改查 函数
 */
class ListViewModel: ObservableObject {
    
    @Published var items: [ItemModel] = [] {
        didSet {
            //每次更改items属性时，我们就调用本地存储
            saveItems()
        }
    }
    
    let itemsKey: String = "items_list"
    
    init() {
        
        getItems()
    }
    
//    查
    private func getItems() {
        
//        let newItems = [
//            ItemModel(title: "这是第一个事项", isCompleted: false),
//            ItemModel(title: "第二个事项", isCompleted: true),
//            ItemModel(title: "事项三3", isCompleted: false)
//        ]
//        items.append(contentsOf: newItems)
        
        guard
            let data = UserDefaults.standard.data(forKey: itemsKey),
            let saveItems = try? JSONDecoder().decode([ItemModel].self, from: data) 
        else { return }
        
        items = saveItems
    }
    
//    增
    func addItem(title: String) {
        let newItem = ItemModel(title: title, isCompleted: false)
        
        items.append(newItem)
    }
    
//    删
    func deleteItem(idnexSet: IndexSet) {
        items.remove(atOffsets: idnexSet)
    }
    
    func moveItem(from: IndexSet, to: Int) {
        items.move(fromOffsets: from, toOffset: to)
    }
    
//    改
    func updateItem(item: ItemModel) {
        if let index = items.firstIndex(where: { $0.id == item.id }) {
            items[index] = item.updateCompletion()
        }
    }
    
    //    本地保存数据
    func saveItems() {
        if let encodedData = try? JSONEncoder().encode(items) {
            UserDefaults.standard.setValue(encodedData, forKey: itemsKey)
        }
    }
}
